import hashlib
import os
import django
import datetime
from django.utils import timezone
import sys

sys.path.append(os.path.dirname(__file__) + os.sep + "../")  # 添加上级目录到环境变量
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "teachzero.settings")  # 处理django环境变量
django.setup()


WHITE_LIST = [".pdf", ".html"]
BLACK_LIST = ["答案", "重点知识", "作业", "课堂练习题"]


class My_blog:
    def __init__(self):
        """
        加载博客数据库
        """

    def load_datas(self):
        from teachzero import settings
        from blog.models import Blog

        datas = []
        for path, dirnames, filenames in os.walk(settings.PATH["blog"]):
            for file in filenames:
                file_type = os.path.splitext(file)[1]
                flag = 1
                if not file_type in WHITE_LIST:
                    flag = 0
                for i in BLACK_LIST:
                    if i in file:
                        flag = 0
                        break
                if flag:
                    real_path = os.path.join(path, file)
                    paths = os.path.normpath(real_path)
                    paths = paths.split(os.sep)
                    tag_index = paths.index("statics") + 2
                    url = os.path.join("/static", *paths[tag_index - 1 :])  # 使用列表做参数
                    mtime = os.path.getmtime(real_path)
                    mtime = datetime.datetime.fromtimestamp(mtime)  # 转换成datetime
                    mtime = timezone.make_aware(mtime, timezone.get_current_timezone())
                    name = os.path.splitext(file)[0]
                    item_dict = {
                        "name": name,
                        "url": url,
                        "path": real_path,
                        "md5": hashlib.md5(
                            (real_path).encode("utf-8")
                        ).hexdigest(),
                        "modified_time": mtime,
                        "tag": paths[tag_index],
                        "show": True,
                    }
                    datas.append(item_dict)
        datas = sorted(datas, key=lambda x: (x["modified_time"]))
        return datas

    def update(self):
        print("update blog")
        """
        更新数据
        """
        from blog.models import Blog

        datas = self.load_datas()
        for blog in Blog.objects.all():
            if not os.path.isfile(blog.path):
                blog.delete()
        for data in datas:
            blog = Blog.objects.filter(path=data["path"])  # 目录一样视为同一条数据
            if blog:
                blog = blog[0]
                blog.url = data["url"]
                blog.path = data["path"]
                blog.md5 = data["md5"]
                blog.tag = data["tag"]
                blog.modified_time = data["modified_time"]
                blog.save()
            else:
                blog = Blog(
                    name=data["name"],
                    url=data["url"],
                    path=data["path"],
                    md5=data["md5"],
                    tag=data["tag"],
                    modified_time=data["modified_time"],
                )
                blog.save()
            print(blog.id, blog.name)


if __name__ == "__main__":
    my_blog = My_blog()
    my_blog.update()
